package tutorial.main.data;



import tutorial.main.control.Utilities;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class RegistroDataBaseHelper extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "registroEventos.db";
	private static final int DATABASE_VERSION = 1;

	private static final String TABLA_EVENTOS = "eventos";
	private static final String TABLA_USUARIOS = "usuarios";


	RegistroDataBaseHelper(Context context) 
	{
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) 
	{
		createDatabaseSchema(db);
	}

	private void createDatabaseSchema(SQLiteDatabase db) 
	{
		StringBuilder createTableSentence = new StringBuilder();
		createTableSentence.append("CREATE  TABLE  IF NOT EXISTS \""+ TABLA_EVENTOS + "\"");
		
		createTableSentence.append("(\"" + Utilities.COLUMN_ID	+ "\" INTEGER PRIMARY KEY NOT NULL , ");
		createTableSentence.append("\"" + Utilities.COLUMN_COD_USUARIO	+ "\" INTEGER NOT NULL , ");
		createTableSentence.append("\""	+ Utilities.COLUMN_ESTADO_CONECTADO + "\" BOOLEAN, \""	+ Utilities.COLUMN_SINCRONIZADO + "\" BOOLEAN, ");
		createTableSentence.append("\""	+ Utilities.COLUMN_MOMENTO + "\" NUMERIC NOT NULL, \""	+ Utilities.COLUMN_TIPO_CONEXION + "\" TEXT, ");
		
		createTableSentence.append("\""	+ Utilities.COLUMN_POSICION_LATITUD + "\" NUMERIC NOT NULL, \""	+ Utilities.COLUMN_POSICION_LONGITUD + "\" NUMERIC NOT NULL, ");
		
		createTableSentence.append("\"" + Utilities.COLUMN_SUBTIPO_CONEXION	+ "\" TEXT , \"" + Utilities.COLUMN_REASON + "\" TEXT  )");
		
		
		Log.v("RegistroDataBaseHelper",createTableSentence.toString());
		Log.v("RegistroDataBaseHelper","Creo la BD de Eventos");
		db.execSQL("DROP TABLE IF EXISTS "+ TABLA_EVENTOS);
		db.execSQL(createTableSentence.toString());

		
		createTableSentence = new StringBuilder();
		createTableSentence.append("CREATE  TABLE  IF NOT EXISTS \"" + TABLA_USUARIOS + "\"");
		createTableSentence.append("(\"" + Utilities.COLUMN_ID	+ "\" INTEGER PRIMARY KEY NOT NULL , ");
		createTableSentence.append("\"" + Utilities.COLUMN_NOMBRE_USUARIO + "\" TEXT NOT NULL ) ");
		
		Log.v("RegistroDataBaseHelper",createTableSentence.toString());
		Log.v("RegistroDataBaseHelper","Creo la BD de Usuarios");
		db.execSQL(createTableSentence.toString());
		
	}

	public long insertarEventos(ContentValues values)
	{
			long a=getWritableDatabase().insert(TABLA_EVENTOS, null, values);
			Log.v("RegistroDataBaseHelper","Inserto Evento");
			return a;
	}
	
	public long actualizarEventos(String[] idsEvents, ContentValues values)
	{		
		long a=getWritableDatabase().update(TABLA_EVENTOS, values, Utilities.COLUMN_ID+ "=?", idsEvents);
		Log.v("RegistroDataBaseHelper","Inserto Evento");
		return a;
	}
	
	public int eliminarEvento(String[] idsEvents)
	{
			int a=getWritableDatabase().delete(TABLA_EVENTOS, Utilities.COLUMN_ID+ "=?",idsEvents);
			Log.v("RegistroDataBaseHelper","Elimino evento Evento");
			return a;
	}
	
	public long insertarUsuario(ContentValues values)
	{
			long a=getWritableDatabase().insert(TABLA_USUARIOS, null, values);
			Log.v("RegistroDataBaseHelper","---Inserto USUARIO");
			return a;
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
	{

	}
	
	/**
	 * Busco los eventos del usuario, segun el id de usuario, y ordenados segun fecha
	 * @param nroUsuario
	 * @return
	 */
	public Cursor getEventosDeUsuario(String nroUsuario) 
	{
		Cursor cursor = getReadableDatabase().query(TABLA_EVENTOS, null,Utilities.COLUMN_COD_USUARIO + "=?",new String[] { nroUsuario }, null, null, Utilities.COLUMN_MOMENTO);
		Log.v("RegistroDataBaseHelper","-Leyo eventos de usuario");
		return cursor;
	}
	
	/**
	 * Busco el idUsuario en la BD segun el nombre de usuario
	 * @param nmbreUsuario
	 * @return
	 */
	public Cursor buscarIdUsuario(String nmbreUsuario) 
	{
		Cursor cursor = getReadableDatabase().query(TABLA_USUARIOS, null,Utilities.COLUMN_NOMBRE_USUARIO + "=?",new String[] { nmbreUsuario }, null, null, null);
		Log.v("RegistroDataBaseHelper","Leyo eventos de usuario");
		return cursor;
	}
	
	public Cursor getUltimoNmro() 
	{
		Cursor cursor = getReadableDatabase().rawQuery("SELECT MAX(" + Utilities.COLUMN_ID+") as "+Utilities.COLUMN_ID+ " FROM "+TABLA_EVENTOS, null);
		return cursor;
	}
	public Cursor getUltimoEvento() 
	{
		Cursor cursor1 = getReadableDatabase().rawQuery("SELECT MAX(" + Utilities.COLUMN_MOMENTO+") as "+Utilities.COLUMN_MOMENTO+ " FROM "+TABLA_EVENTOS, null);
		long ult=0;		
		if (cursor1 != null) {
			
		    cursor1.moveToLast();
		    int idIndex= cursor1.getColumnIndex(Utilities.COLUMN_MOMENTO);
		    if(idIndex!=-1)
		    {
		    	ult=cursor1.getLong(idIndex);
		    }
			cursor1.close();
		}
		
		Cursor cursor = getReadableDatabase().rawQuery(" SELECT * FROM "+TABLA_EVENTOS+" WHERE "+Utilities.COLUMN_MOMENTO+"='"+ult+"'",null);
		//Cursor cursor = getReadableDatabase().query(TABLA_EVENTOS, null,Utilities.COLUMN_MOMENTO + "=?"  ,new String[] {"SELECT MAX(" + Utilities.COLUMN_MOMENTO+") as "+Utilities.COLUMN_MOMENTO+ " FROM "+TABLA_EVENTOS }, null, null, null);
		
		return cursor;
	}
	
}
